package com.bcx.crm.java.pinyin;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * Created by ys on 2018/3/27.
 */
public class HanYuUtil {
    public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
        String s = HanYuUtil.strFirst2Pinyin("ssss");
        String s1 = HanYuUtil.str2Pinyin("说的", "士大夫");
    }
    private static final HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
    static {
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
    }
    //输入拼音判断其中文
    public static String str2Pinyin(String str , String fill) throws BadHanyuPinyinOutputFormatCombination {
        StringBuilder stringBuilder = new StringBuilder();
        //判断是中文
        boolean isCn = true;
        if (null == fill){
            fill = " ";
        }
        for (int i = 0; i <str.length() ; i++) {
            char c = str.charAt(i);
            if (c == ' '){
                stringBuilder.append(",");
            }
            //1.判断是不是中文
            if (i>0 && isCn){
                stringBuilder.append(fill);
            }
            if(c>='\u4e00'&&i<='\u9fa5'){
                isCn = true;
                stringBuilder.append(PinyinHelper.toHanyuPinyinStringArray(c,format)[0]);
            }else {
                //不是中文
                if ((c>='a' && c<='z')||(c>='A' && c<='Z')){
                    stringBuilder.append(c);
                    isCn = false;
                }
            }
        }
        return stringBuilder.toString();
    }
    public static String strFirst2Pinyin(String str) throws BadHanyuPinyinOutputFormatCombination {
        StringBuffer stringBuffer = new StringBuffer();
        //判断是中文
        for (int i=0;i<str.length();i++){
            char c = str.charAt(i);
            if(c>='\u4e00'&&i<='\u9fa5'){ //判断是不是汉字
                stringBuffer.append(PinyinHelper.toHanyuPinyinStringArray(c,format)[0]);
            }
        }
        return stringBuffer.toString();
    }
}
